package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.websocket.annotation.Online;
import com.ruoyi.framework.web.service.IdCardService;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.UserCardService;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wq.domain.WqIpBlack;
import com.ruoyi.wq.domain.WqUserRecord;
import com.ruoyi.wq.service.IWqIpBlackService;
import com.ruoyi.wq.service.IWqUserRecordService;
import com.ruoyi.wx.domain.WxApp;
import com.ruoyi.wx.service.IWxAppService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;
    
    @Autowired
    private ISysConfigService sysConfigService;
    
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;
    
    @Autowired
	private IWxAppService wxAppService;
    
    @Autowired
    private SysLoginService sysLoginService;
    
    @Autowired
    private IdCardService idCardService;
    
    @Autowired
    private UserCardService userCardService;
    
    @Autowired
    private IWqIpBlackService wqIpBlackService;
    
    @Autowired
    private IWqUserRecordService wqUserRecordService;
    
    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }
    
    /**
     * 获取用户列表
     */
    @GetMapping("/getList")
    public TableDataInfo getList(SysUser user){
    	TableDataInfo info = userService.getPageList(user);
        return info;
    }
    
    /**
     * 获取推荐用户列表
     */
    @Anonymous
    @GetMapping("/getListByOpen")
    public TableDataInfo getListByOpen(SysUser user){
    	TableDataInfo info = userService.getListByOpen(user);
        return info;
    }
    
    /**
     * 获取推荐用户列表
     */
    @Anonymous
    @GetMapping("/getUserListByOpen")
    public TableDataInfo getUserListByOpen(SysUser user){
    	if("wx05c9893288d3dd64".equals(user.getAppId())){
			return userService.getUserListByOpen(user);
		}
    	TableDataInfo info = userService.getUserListOtherByOpen(user);
        return info;
    }
    
    /**
     * 获取推荐用户列表
     */
    @GetMapping("/getListByHot")
    public TableDataInfo getListByHot(SysUser user){
    	TableDataInfo info = userService.getPageListByHot(user);
        return info;
    }
    
    /**
     * 获取推荐用户列表
     */
    @Anonymous
    @GetMapping("/getListByTopic")
    public TableDataInfo getListByTopic(SysUser user){
        return null;
    }
    
    /**
     * 获取陪玩列表
     */
    @Anonymous
    @GetMapping("/getListByPlay")
    public TableDataInfo getListByPlay(SysUser user){
    	TableDataInfo info = userService.getPageListByPlay(user);
        return info;
    }
    
    /**
     * 获取陪玩申请列表
     */
    @GetMapping("/getListByApply")
    public TableDataInfo getListByApply(SysUser user){
    	TableDataInfo info = userService.getPageListByApply(user);
        return info;
    }
    
    /**
     * 获取脱单用户列表
     */
    @Anonymous
    @GetMapping("/getListByIdCard")
    public TableDataInfo getListByIdCard(SysUser user){
    	TableDataInfo info = userService.getPageListByIdCard(user);
        return info;
    }
    
    /**
     * 获取推荐用户列表
     */
    @GetMapping("/getListByPage")
    public TableDataInfo getListByPage(SysUser user){
    	TableDataInfo info = userService.getListByPage(user);
        return info;
    }
    
    /**
     * 获取推荐用户列表
     */
    @GetMapping("/getListByTop")
    public TableDataInfo getListByTop(SysUser user){
    	TableDataInfo info = userService.getPageListByTop(user);
        return info;
    }
    
    /**
     * 获取同城用户列表
     */
    @GetMapping("/getListByCity")
    public TableDataInfo getListByCity(SysUser user){
    	TableDataInfo info = userService.getPageListByCity(user);
        return info;
    }
    
    /**
     * 获取同城用户列表
     */
    @Anonymous
    @GetMapping("/getUserListByCity")
    public TableDataInfo getUserListByCity(SysUser user){
    	TableDataInfo info = userService.getPageUserListByCity(user);
        return info;
    }
    
    /**
     * 获取达人用户列表
     */
    @Anonymous
    @GetMapping("/getListByFans")
    public TableDataInfo getListByFans(SysUser user){
        startPage();
        List<SysUser> list = userService.selectListByFans(user);
        return getDataTable(list);
    }
    
    /**
     * 获取会员用户列表
     */
    @GetMapping("/getListByVip")
    public TableDataInfo getListByVip(SysUser user){
    	TableDataInfo info = userService.getPageListByVip(user);
        return info;
    }
    
    /**
     * 获取贵族用户列表
     */
    @GetMapping("/getListByPayNum")
    public TableDataInfo getListByPayNum(SysUser user){
    	TableDataInfo info = userService.getListByPayNum(user);
        return info;
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo(){
        Long userId = SecurityUtils.getUserId();
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.getById(userId);
        
        if(StringUtils.isNotBlank(user.getScene())){
        	WqIpBlack ipBlack = wqIpBlackService.getIpBlack(user.getScene());
        	if(ipBlack != null){
        		user.setIsAuth("1");
        	}
        }
        
        if(user.getVisitUserId() != null){
        	user.setIsAuth("1");
        }
		if(StringUtils.isNotBlank(user.getPhonenumber())){
			user.setIsAuth("1");
		}
		if(StringUtils.isNotBlank(user.getWxOpenId())){
			user.setIsAuth("1");
		}
		if(user.getPayNum() > 10){
			user.setIsAuth("1");
		}
		SysConfig config = sysConfigService.getConfig(user.getAppId());
		user.setIsAgent(config.getIsFans());
		
        ajax.put("user", user);
        
        List<String> tmplIds = new ArrayList<>();
    	if(StringUtils.isNotBlank(user.getAppId())){
    		WxApp wxApp = wxAppService.getByAppid(user.getAppId());
    		tmplIds.add(wxApp.getOneTemplateId());
    	}
    	ajax.put("tmplIds", tmplIds);
        return ajax;
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @Online
    @GetMapping("getMyInfo")
    public AjaxResult getMyInfo(){
        Long userId = SecurityUtils.getUserId();
        AjaxResult ajax = AjaxResult.success();
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        SysUser user = userService.getMyInfo(sysUser);
        
        if(StringUtils.isNotBlank(user.getScene())){
        	WqIpBlack ipBlack = wqIpBlackService.getIpBlack(user.getScene());
        	if(ipBlack != null){
        		user.setIsAuth("1");
        	}
        }
        
        if(user.getVisitUserId() != null){
        	user.setIsAuth("1");
        }
		if(StringUtils.isNotBlank(user.getWxOpenId())){
			user.setIsAuth("1");
		}
		if(user.getPayNum() > 10){
			user.setIsAuth("1");
		}
		SysConfig config = sysConfigService.getConfig(user.getAppId());
		user.setIsAgent(config.getIsFans());
        ajax.put("user", user);
        
        List<String> tmplIds = new ArrayList<>();
    	if(StringUtils.isNotBlank(user.getAppId())){
    		WxApp wxApp = wxAppService.getByAppid(user.getAppId());
    		tmplIds.add(wxApp.getOneTemplateId());
    	}
    	ajax.put("tmplIds", tmplIds);
        return ajax;
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @Online
    @GetMapping("getMyAsk")
    public AjaxResult getMyAsk(){
    	AjaxResult ajax = AjaxResult.success();
        Long userId = SecurityUtils.getUserId();
        SysUser user = userService.getById(userId);
        user.setIsDog("0");
        userService.updateById(user);
        return ajax;
    }
    
    @GetMapping("getRandomUser")
    public AjaxResult getRandomUser() {
    	SysUser user = userService.getRandomAskUser(SecurityUtils.getUserId());
    	return AjaxResult.success(user);
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @Online
    @GetMapping("getMyUserInfo")
    public AjaxResult getMyUserInfo(){
        Long userId = SecurityUtils.getUserId();
        AjaxResult ajax = AjaxResult.success();
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        SysUser user = userService.getMyInfo(sysUser);
        
        Integer shareCount = userService.getShareUserCount(userId);
        
        WqUserRecord userRecord = wqUserRecordService.getById(userId);
        if(userRecord != null){
        	if(!"0".equals(userRecord.getStatus())){
        		user.setIsWelcome(1);
        	}
        }
        
        if(StringUtils.isNotBlank(user.getScene())){
        	WqIpBlack ipBlack = wqIpBlackService.getIpBlack(user.getScene());
        	if(ipBlack != null){
        		user.setIsAuth("1");
        	}
        }
        
        if(user.getVisitUserId() != null){
        	user.setIsAuth("1");
        }
        if(StringUtils.isNotBlank(user.getPhonenumber())){
			user.setIsAuth("1");
		}
		if(StringUtils.isNotBlank(user.getWxOpenId())){
			user.setIsAuth("1");
		}
		if(user.getPayNum() > 10){
			user.setIsAuth("1");
		}
		SysConfig config = sysConfigService.getConfig(user.getAppId());
		user.setIsAgent(config.getIsFans());
        
        ajax.put("user", user);
        ajax.put("shareCount", shareCount);
        return ajax;
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @Anonymous
    @GetMapping("getTmplId")
    public AjaxResult getTmplId(String appId){
    	AjaxResult ajax = AjaxResult.success();
        List<String> tmplIds = new ArrayList<>();
        WxApp wxApp = wxAppService.getByAppid(appId);
		tmplIds.add(wxApp.getOneTemplateId());
		SysConfig config = sysConfigService.getConfig(appId);
    	ajax.put("tmplIds", tmplIds);
    	ajax.put("isTip", config.getIsTip());
    	
    	String loginIp = IpUtils.getIpAddr(ServletUtils.getRequest());
    	if(StringUtils.isNotBlank(loginIp)){
        	WqIpBlack ipBlack = wqIpBlackService.getIpBlack(loginIp);
        	if(ipBlack == null){
        		ajax.put("isLogin", config.getConfigValue());
        	}else{
        		ajax.put("isLogin", "0");
        	}
        }
        return ajax;
    }
    
    @GetMapping("getMyTip")
    public AjaxResult getMyTip(){
        Long userId = SecurityUtils.getUserId();
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.getById(userId);
        user.setTipNum(user.getTipNum()+1);
        userService.updateById(user);
        return ajax;
    }
    
    @Anonymous
    @GetMapping("getMyOpenTip")
    public AjaxResult getMyOpenTip(Long userId){
        AjaxResult ajax = AjaxResult.success();
        if(userId != null){
        	SysUser user = userService.getById(userId);
            user.setTipNum(user.getTipNum()+1);
            userService.updateById(user);
        }
        return ajax;
    }
    
    /**
     * 获取分享二维码信息
     * 
     * @return 用户信息
     */
    @GetMapping("getShare")
    public AjaxResult getShare(){
        AjaxResult ajax = AjaxResult.success();
        SysUser user = sysLoginService.getShare();
        ajax.put("user", user);
        return ajax;
    }
    
    /**
     * 获取用户会员次数信息
     * 
     * @return 用户信息
     */
    @Online
    @GetMapping("getMyNum")
    public AjaxResult getMyNum(){
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.getMyNum();
        ajax.put("user", user);
        
        List<String> tmplIds = new ArrayList<>();
    	if(StringUtils.isNotBlank(user.getAppId())){
    		WxApp wxApp = wxAppService.getByAppid(user.getAppId());
    		tmplIds.add(wxApp.getOneTemplateId());
    	}
    	ajax.put("tmplIds", tmplIds);
        return ajax;
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @Online
    @GetMapping("getInfoById")
    public AjaxResult getInfo(SysUser user){
        AjaxResult ajax = AjaxResult.success();
        // 增加访客记录
        sysLoginService.addVisit(user.getUserId());
        SysUser sysUser = userService.getInfoById(user);
        if("1".equals(sysUser.getStatus())){
        	throw new ServiceException("对方账号多次违规");
        }
        ajax.put("user", sysUser);
        return ajax;
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @Anonymous
    @GetMapping("getInfoByUserId")
    public AjaxResult getInfoByUserId(SysUser user){
        AjaxResult ajax = AjaxResult.success();
        // 增加访客记录
        sysLoginService.addVisitUser(user.getUserId(), user.getVisitUserId());
        SysUser sysUser = userService.getInfoByUserId(user);
        if("1".equals(sysUser.getStatus())){
        	throw new ServiceException("对方账号多次违规");
        }
        ajax.put("user", sysUser);
        return ajax;
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getUserInfoById")
    public AjaxResult getUserInfoById(SysUser user){
        AjaxResult ajax = AjaxResult.success();
        // 增加访客记录
        sysLoginService.addVisit(user.getUserId());
        SysUser sysUser = userService.getInfoById(user);
        if("1".equals(sysUser.getStatus())){
        	throw new ServiceException("对方账号多次违规");
        }
        ajax.put("user", sysUser);
        return ajax;
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @Anonymous
    @GetMapping("getWxOpenIdById")
    public AjaxResult getWxOpenIdById(SysUser user){
        AjaxResult ajax = AjaxResult.success();
        SysUser sysUser = userService.getWxOpenIdById(user);
        ajax.put("user", sysUser);
        return ajax;
    }
    
    /**
     * 添加黑名单
     * 
     * @return 用户信息
     */
    @PostMapping("/addBlack")
    public AjaxResult addBlack(@RequestBody SysUser user){
    	SysUser sysUser = userService.getById(SecurityUtils.getUserId());
    	if("otgJw5zsvpjKb5Zqar426FpoRVTY".equals(sysUser.getUnionId())){
    		sysLoginService.addBlack(user);
    	}else{
    		sysLoginService.addImBlackUser(user);
    	}
        return AjaxResult.success();
    }
    
    /**
     * 添加用户黑名单
     * 
     * @return 用户信息
     */
    @PostMapping("/addUserBlack")
    public AjaxResult addUserBlack(@RequestBody SysUser user){
    	SysUser sysUser = userService.getById(SecurityUtils.getUserId());
    	if("1".equals(sysUser.getIsManager())){
    		sysLoginService.addUserBlack(user);
    	}else{
    		sysLoginService.addUserImBlackUser(user);
    	}
        return AjaxResult.success();
    }
    
    /**
     * 资料通过
     * 
     * @return 用户信息
     */
    @PostMapping("/addUserPass")
    public AjaxResult addUserPass(@RequestBody SysUser user){
    	SysUser sysUser = userService.getById(SecurityUtils.getUserId());
    	if("1".equals(sysUser.getIsManager())){
    		sysLoginService.addUserPass(user);
    	}
        return AjaxResult.success();
    }
    
    /**
     * 添加陪玩
     * 
     * @return 用户信息
     */
    @PostMapping("/addPlayStatus")
    public AjaxResult addPlayStatus(@RequestBody SysUser user){
    	userService.addPlayStatus(user);
        return AjaxResult.success();
    }
    
    /**
     * 申请达人
     * 
     * @return 用户信息
     */
    @PostMapping("/addIsTip")
    public AjaxResult addIsTip(@RequestBody SysUser user){
    	userService.addIsTip(user);
        return AjaxResult.success();
    }
    
    /**
     * 永久封号
     * 
     * @return 用户信息
     */
    @PostMapping("/addBlackUser")
    public AjaxResult addBlackUser(@RequestBody SysUser user){
    	SysUser sysUser = userService.getById(SecurityUtils.getUserId());
    	if("otgJw5zsvpjKb5Zqar426FpoRVTY".equals(sysUser.getUnionId())){
    		sysLoginService.addBlackUser(user);
    	}else{
    		sysLoginService.addImBlackUser(user);
    	}
        return AjaxResult.success();
    }
    
    /**
     * 永久封号
     * 
     * @return 用户信息
     */
    @PostMapping("/addUserBlackUser")
    public AjaxResult addUserBlackUser(@RequestBody SysUser user){
    	SysUser sysUser = userService.getById(SecurityUtils.getUserId());
    	if("1".equals(sysUser.getIsManager())){
    		sysLoginService.addUserBlackUser(user);
    	}else{
    		sysLoginService.addUserImBlackUser(user);
    	}
        return AjaxResult.success();
    }
    
    /**
     * 申请注销
     * 
     * @return 用户信息
     */
    @PostMapping("/addLogout")
    public AjaxResult addLogout(){
    	SysUser user = new SysUser();
    	user.setUserId(SecurityUtils.getUserId());
    	sysLoginService.addBlackUser(user);
        return AjaxResult.success();
    }
    
    /**
     * 实名认证
     * 
     * @return 用户信息
     */
    @PostMapping("/idCard")
    public AjaxResult idCard(){
    	idCardService.idCard(SecurityUtils.getUserId());
        return AjaxResult.success();
    }
    
    /**
     * 实名认证
     * 
     * @return 用户信息
     */
    @PostMapping("/idCardPhone")
    public AjaxResult idCardPhone(@RequestBody SysUser user){
    	idCardService.idCardPhone(user.getPhonenumber());
        return AjaxResult.success();
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }
    
    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }
}
